/*
 * @Author: Leo.wang wanglizhigs@163.com
 * @Date: 2025-07-02 22:08:23
 * @LastEditors: Leo.wang wanglizhigs@163.com
 * @LastEditTime: 2025-07-02 23:30:36
 * @FilePath: /book-manage-angular/src/app/pages/order-process/order-process.component.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https:
 */
import { Component, OnInit, OnDestroy, NgZone } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { CommonModule } from '@angular/common';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalModule } from 'ng-zorro-antd/modal';
import { NzModalService } from 'ng-zorro-antd/modal';
import { NzAlertModule } from 'ng-zorro-antd/alert';
import { NzFormModule } from 'ng-zorro-antd/form';
import { NzSelectModule } from 'ng-zorro-antd/select';
import { NzInputNumberModule } from 'ng-zorro-antd/input-number';
import { NzButtonModule } from 'ng-zorro-antd/button';
import { NzGridModule } from 'ng-zorro-antd/grid';
import { NzTableModule } from 'ng-zorro-antd/table';
import { NzRadioModule } from 'ng-zorro-antd/radio';
import { NzTagModule } from 'ng-zorro-antd/tag';
import { NzProgressModule } from 'ng-zorro-antd/progress';
import { KeyStrategyDisplayComponent } from '../../components/key-strategy-display/key-strategy-display.component'
import { setStrategyType, getStrategyType } from '../../utils/keyTypeStore'

interface Order {
  id: string;
  bookName: string;
  userName: string;
  type: string;
  status: string;
  progress: number;
  createTime: string;
  updateTime: string;
  checked: boolean
}

@Component({
  selector: 'app-order-process',
  templateUrl: './order-process.component.html',
  styleUrls: ['./order-process.component.less'],
  imports: [
    FormsModule,
    CommonModule,
    NzModalModule,
    NzAlertModule,
    NzFormModule,
    NzSelectModule,
    NzInputNumberModule,
    NzButtonModule,
    NzGridModule,
    NzTableModule,
    NzRadioModule,
    NzTagModule,
    NzProgressModule,
    KeyStrategyDisplayComponent
  ],
})
export class OrderProcessComponent implements OnInit, OnDestroy {

  orderStatus: string = '全部';
  updateInterval: number = 1000;
  isUpdating: boolean = false;
  updateTimer: any = null;

  displayData: Order[] = [];
  selectedOrders: Order[] = [];

  pendingCount: number = 0;
  processingCount: number = 0;
  completedToday: number = 0;
  efficiency: number = 95;
  keyType: string = 'id';

  constructor(
    private message: NzMessageService,
    private modalService: NzModalService,
    private ngZone: NgZone
  ) {
    this.keyType = getStrategyType()
  }


  generateMockOrder(idx: number): Order {
    const types = ['借阅', '归还', '预约', '续借'];
    const statuses = ['待处理', '处理中', '已完成', '已取消'];
    const books = [
      'JavaScript高级程序设计',
      'Python数据分析',
      '深入理解计算机系统',
      '算法导论',
      '设计模式',
      '代码整洁之道',
      'Vue.js实战',
      'React设计模式',
    ];
    const users = [
      '张三',
      '李四',
      '王五',
      '赵六',
      '钱七',
      '孙八',
      '周九',
      '吴十',
    ];

    return {
      id: `ORD${String(idx + 1).padStart(6, '0')}`,
      bookName: books[Math.floor(Math.random() * books.length)],
      userName: users[Math.floor(Math.random() * users.length)],
      type: types[Math.floor(Math.random() * types.length)],
      status: statuses[Math.floor(Math.random() * statuses.length)],
      progress: Math.floor(Math.random() * 100),
      createTime: new Date(
        Date.now() - Math.floor(Math.random() * 86400000)
      ).toLocaleString(),
      updateTime: new Date().toLocaleString(),
      checked: false
    };
  }


  get filteredData(): Order[] {
    if (!this.orderStatus) {
      return this.displayData;
    }

    if (this.orderStatus === '全部') {
      return this.displayData;
    }
    return this.displayData.filter(order => order.status === this.orderStatus)
  }


  startUpdate(): void {
    this.isUpdating = true;
    this.updateTimer = setInterval(() => {
      this.generateOrderData(); // Regenerate data at the specified interval
    }, this.updateInterval);
  }


  stopUpdate(): void {
    this.isUpdating = false;
    if (this.updateTimer) {
      clearInterval(this.updateTimer);
      this.updateTimer = null;
    }
  }


  handleIntervalChange(): void {
    if (this.isUpdating) {
      this.stopUpdate();
      this.startUpdate();
    }
  }


  toggleUpdate(): void {
    if (this.isUpdating) {
      this.stopUpdate();
    } else {
      this.startUpdate();
    }
  }

  handleBatchProcess(): void {
    const list = this.displayData.filter(item => item.checked)
    if (list.length === 0) {
      this.message.warning('请先选择要处理的订单');
      return;
    }
    this.message.success(`批量处理 ${list.length} 个订单`);
    // In a real application, this would send an array of order IDs to a batch processing API
  }


  generate2000Orders(): void {
    // Use NgZone.runOutsideAngular to prevent unnecessary change detection cycles during data generation
    // which can interfere with accurate performance timing.
    this.ngZone.runOutsideAngular(() => {
      const start = performance.now();
      this.displayData = Array.from({ length: 2000 }, (_, idx) =>
        this.generateMockOrder(idx)
      );
      // Run updateStats inside Angular's zone to trigger change detection for stats display
      this.ngZone.run(() => {
        this.updateStats();
        const end = performance.now();
        this.message.success(
          `生成2000条订单耗时：${(end - start).toFixed(2)}ms`
        );
      });
    });
  }

  insertRandomOrder(): void {
    this.ngZone.runOutsideAngular(() => {
      const start = performance.now();
      const idx = Math.floor(Math.random() * (this.displayData.length + 1));
      const newOrder = this.generateMockOrder(this.displayData.length); // Use current length for unique ID
      const newDisplayData = [...this.displayData]; // Create a new array reference
      newDisplayData.splice(idx, 0, newOrder);
      this.ngZone.run(() => {
        this.displayData = newDisplayData;
        this.updateStats();
        const end = performance.now();
        this.message.success(`插入订单耗时：${(end - start).toFixed(2)}ms`);
      });
    });
  }

  deleteRandomOrder(): void {
    if (this.displayData.length === 0) {
      this.message.warning('没有订单可删除。');
      return;
    }
    this.ngZone.runOutsideAngular(() => {
      const start = performance.now();
      const idx = Math.floor(Math.random() * this.displayData.length);
      const newDisplayData = [...this.displayData]; // Create a new array reference
      newDisplayData.splice(idx, 1);
      this.ngZone.run(() => {
        this.displayData = newDisplayData;
        this.updateStats();
        const end = performance.now();
        this.message.success(`删除订单耗时：${(end - start).toFixed(2)}ms`);
      });
    });
  }


  replaceAllOrders(): void {
    this.ngZone.runOutsideAngular(() => {
      const start = performance.now();
      const len = this.displayData.length;
      this.displayData = Array.from({ length: len }, (_, idx) =>
        this.generateMockOrder(idx)
      );
      this.ngZone.run(() => {
        this.updateStats();
        const end = performance.now();
        this.message.success(`替换所有订单耗时：${(end - start).toFixed(2)}ms`);
      });
    });
  }


  shuffleOrders(): void {
    this.ngZone.runOutsideAngular(() => {
      const start = performance.now();
      const arr = [...this.displayData]; // Create a shallow copy to avoid direct mutation issues
      for (let i = arr.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [arr[i], arr[j]] = [arr[j], arr[i]]; // ES6 array destructuring for swap
      }
      this.ngZone.run(() => {
        this.displayData = arr;
        const end = performance.now();
        this.message.success(`打乱顺序耗时：${(end - start).toFixed(2)}ms`);
      });
    });
  }

  onAllChecked(checked: boolean) {
    console.log('onAllChecked', checked)
    const list = this.displayData.map(item => {
      item.checked = checked
      return item;
    })
    this.displayData = [...list]

    // this.listOfCurrentPageData
    //   .filter(({ disabled }) => !disabled)
    //   .forEach(({ id }) => this.updateCheckedSet(id, checked));
    // this.refreshCheckedStatus();
  }

  onItemChecked(data: Order, checked: boolean) {
    console.log('onItemChecked', data, checked)
    // this.updateCheckedSet(id, checked);
    // this.refreshCheckedStatus();
  }


  generateOrderData() {
    const types = ['借阅', '归还', '预约', '续借'];
    const statuses = ['待处理', '处理中', '已完成', '已取消'];
    const books = [
      'JavaScript高级程序设计',
      'Python数据分析',
      '深入理解计算机系统',
      '算法导论',
      '设计模式',
      '代码整洁之道',
      'Vue.js实战',
      'React设计模式',
    ];
    const users = [
      '张三',
      '李四',
      '王五',
      '赵六',
      '钱七',
      '孙八',
      '周九',
      '吴十',
    ];

    this.displayData = Array(20)
      .fill(null)
      .map((_, index) => ({
        id: `ORD${String(index + 1).padStart(6, '0')}`,
        bookName: books[Math.floor(Math.random() * books.length)],
        userName: users[Math.floor(Math.random() * users.length)],
        type: types[Math.floor(Math.random() * types.length)],
        status: statuses[Math.floor(Math.random() * statuses.length)],
        progress: Math.floor(Math.random() * 100),
        createTime: new Date(
          Date.now() - Math.floor(Math.random() * 86400000)
        ).toLocaleString(),
        updateTime: new Date().toLocaleString(),
        checked: false
      }));

    this.updateStats();
  }

  updateStats() {
    this.pendingCount = this.displayData.filter(
      (order) => order.status === '待处理'
    ).length;
    this.processingCount = this.displayData.filter(
      (order) => order.status === '处理中'
    ).length;

    this.completedToday = this.displayData.filter(
      (order) => order.status === '已完成'
    ).length;
    this.efficiency = Math.floor(Math.random() * 10 + 90);
  }

  getOrderType(type: string): string {
    const types: { [key: string]: string } = {
      借阅: '#2db7f5',
      归还: '#87d068',
      预约: '#f50',
      续借: '#108ee9',
    };
    return types[type] || '#108ee9';
  }

  getStatusType(status: string): string {
    const types: { [key: string]: string } = {
      待处理: 'pending',
      处理中: 'processing',
      已完成: 'completed',
      已取消: 'cancelled',
    };
    return types[status] || 'info';
  }

  getProgressStatus(progress: number): any {
    if (progress >= 100) return 'success';
    if (progress >= 80) return 'exception';
    return 'normal';
  }

  handleProcess(order: Order) {
    this.message.success(`开始处理订单：${order.id}`);
  }

  handleCancel(order: Order) {
    // this.modalService.confirm({
    //   nzTitle: '确认取消该订单吗？',
    //   nzContent: '此操作不可逆，请谨慎。',
    //   nzOkText: '确定',
    //   nzCancelText: '取消',
    //   nzOnOk: () => {
    //     this.message.success(`已取消订单：${order.id}`);
    //   },
    //   nzOnCancel: () => {},
    // });
  }

  handleDetail(order: Order) {
    this.message.info(`查看订单详情：${order.id}`);
  }

  ngOnInit() {
    this.generateOrderData();
  }

  ngOnDestroy() { }
}
